// ws instance
let connection: WebSocket
let userId :null|string = null // 存放当前用户的id用于绑定
// 重连次数上限
const reconnectCountMax = 100
let reconnectCount = 0

// 初始化 ws 连接 + 监听
export const initConnection = () => {
    // console.log("未开始");
    connection?.removeEventListener('message', onConnectGetMsg)
    connection?.removeEventListener('open', onConnectOpen)
    connection?.removeEventListener('close', onConnectClose)
    connection?.removeEventListener('error', onConnectError)
    // console.log('userId',userId);
    // console.log('连接',`ws://localhost:8081/chat${userId ? `?userId=${userId}` : ''}`);
    //ws://localhost:8081/chat?userId=1
    // 建立链接
    // 本地配置到 .env 里面修改。生产配置在 .env.production 里面
    // connection = new WebSocket(`ws://localhost:10001/chat${userId ? `?userId=${userId}` : ''}`);
    connection = new WebSocket(`ws://120.26.146.100:10001/chat${userId ? `?userId=${userId}` : ''}`);
    // connection = new WebSocket(`ws://120.26.146.100:8081/chat${userId ? `?userId=${userId}` : ''}`);
    // 收到消息
    connection.addEventListener('message', onConnectGetMsg)
    // 建立链接
    connection.addEventListener('open', onConnectOpen)
    // 关闭连接
    connection.addEventListener('close', onConnectClose)
    // 连接错误
    connection.addEventListener('error', onConnectError)
}

//重连机制
export const onIsConnect = (id:any) =>{
    //判断是否断开连接了
    if (connection == null || connection.readyState !== WebSocket.OPEN){
        userId = id;
        initConnection();
    }
}


// 发消息给主进程（window.addEventListener）//后端传回一个json字符串
const postMsg = ( value?: string ) => {
    self.postMessage(value)
}

//接受到服务端发过来的消息
const onConnectGetMsg = (e: any) =>{
    //postMsg(e.data);
    console.log("连接 接收到消息了",e.data);
    const message = JSON.parse(e.data);
    //判断消息是什么类型，好友申请，群聊，还是单聊
    if(2 == message.messageType){//添加好友的信息
        console.log("添加好友的信息",message);
        // 创建自定义事件(连接成功事件)
        // 分发自定义事件
        const haveApplyEvent = new CustomEvent('haveApply', { detail: message });
        window.dispatchEvent(haveApplyEvent);

    }else if(3 == message.messageType){//添加好友信息(回复)
        console.log("添加好友信息(回复)");
        const haveApplyResEvent = new CustomEvent('haveApplyRes', { detail: message });
        window.dispatchEvent(haveApplyResEvent);


    }else if(4 == message.messageType || 5 == message.messageType || 6 == message.messageType || 7 == message.messageType ||  8 == message.messageType){//私聊信息|群聊信息
        console.log("私聊信息|群聊信息");
        // 创建自定义事件(连接成功事件)
        // 分发自定义事件
        const haveApplyEvent = new CustomEvent('chat', { detail: message });
        window.dispatchEvent(haveApplyEvent);
    }
}

//连接成功后触发该方法，可以发送一个消息给服务端(比如建立绑定channel)
//（window.addEventListener自定义的）
const onConnectOpen = (e: any) =>{
    // postMsg({ type: 'open' });
    // 创建自定义事件(连接成功事件)
    // const openConnectEvent = new Event('openConnect');
    // 分发自定义事件
    // window.dispatchEvent(openConnectEvent);
    console.log("连接成功的触发open被调用",e.data);
}

//相当于连接关闭(感知到连接关闭)
const onConnectClose = (e: any) =>{
    // postMsg({ type: 'close' });
    postMsg('close');
    console.log("连接关闭的触发close被调用",e.data);
    connection?.close();
    //连接关闭发送一个消息type=1表示需要解绑，uid-channel （关闭好像不能发送？）
    //connection?.send(JSON.stringify({type: 1,value:userStoreAPI.getCurrentUser().id}))
}

// ws 连接 error 连接失败触发该方法
const onConnectError = () => {
    // onCloseHandler()
    // postMsg({ type: 'error' });
    postMsg('error');
    //todo 尝试重新连接
    console.log("连接失败的触发error被调用");
}

// 往 ws 发消息 绑定  (这里不需要了)
//过期
// export const connectionSendBind = (uid:any) => {
//     console.log('uid',uid);
//     const object = {type:0,uid:uid};
//     connection?.send(JSON.stringify(object));
// }

//发送好友申请消息
export const connectionSendAddApply = async (uid:any , content: string,toUid:any) => {
    const object = {type:2,uid:uid,content:content,toUid:toUid};
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送回复好友申请消息
export const connectionSendAddApplyRes = async (uid:any , content: string,toUid:any,fromName:string,toName:string) => {
    const object = {"type":3,"uid":uid,"content":content,"toUid":toUid,"fromName":fromName,"toName":toName};
    //todo 校验是否断开，断开则重新连接
    console.log("connection",connection)
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}


//发送私聊消息
export const connectionSendFriendChat =  async (uid:any , content: string,toUid:any) => {
    const object = {type:4,uid:uid,content:content,toUid:toUid};
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送群聊消息
export const connectionSendTeamChat= async (uid:any , content: string,teamId:any) => {
    const object = {type:5,uid:uid,content:content,teamId:teamId};
    //todo 校验是否断开，断开则重新连接
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送私聊表情包
export const connectionSendFriendChatEmoji =  async (uid:any , content: string,toUid:any) => {
    const object = {type:6,uid:uid,content:content,toUid:toUid};
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}

//发送群聊消息
export const connectionSendTeamChatEmoji = async (uid:any , content: string,teamId:any) => {
    const object = {type:7,uid:uid,content:content,teamId:teamId};
    if (connection != null && connection.readyState ===  WebSocket.OPEN){
        connection?.send(JSON.stringify(object));
    }else {
        userId = uid;
        await initConnection();
        connection?.send(JSON.stringify(object));
    }
}


//登录成功后接收初始化消息
self.onmessage = (e: MessageEvent<string>) => {
    const { type, value } = JSON.parse(e.data)
    switch (type) {
        case 'initWS': {
            reconnectCount = 0;
            userId = value
            initConnection()
            break
        }
    }
}

